/**
 * add upload support
 */
import Http from "axios";
import ResourceApi from "@/api/manage/resource";
import Images from "../utils/Images";

const OSS = require("ali-oss");

export default {
  data() {
    return {
      showProgress: false,
      files: []
    };
  },
  props: {},
  methods: {
    onExceed: function() {
      this.$message.error("最多上传5个文件!");
    },
    doChange: function() {},
    doUpload: function(file) {
      this.showProgress = true;
      this.files.push({
        id: file.file.uid,
        name: file.file.name,
        percent: 0
      });
      this.image2Base64(file, thumbnail => {
        var resource = {
          name: file.file.name,
          size: file.file.size,
          thumbnail: thumbnail
        };
        ResourceApi.policy(resource).then(res => {
          if (!res.obj.accessSecret) {
            this.doUploadOss(file, res.obj);
          } else {
            this.doUploadOss_chunk(file, res.obj);
          }
        });
      });
    },
    image2Base64: function(file, end) {
      if (file.file.type.indexOf("image/") >= 0) {
        Images.toBase64(file.file, base64 => {
          end && end(base64);
        });
      } else {
        end && end("");
      }
    },
    doUploadOss_chunk: function(file, param) {
      let Oss_client = new OSS({
        region: param.region,
        accessKeyId: param.accessid,
        accessKeySecret: param.accessSecret,
        bucket: param.bucket
      });
      Oss_client.multipartUpload(param.key, file.file, {
        progress: percent => {
          this.doShowProgress(file, parseInt(percent * 100));
        }
      })
        .then(() => {
          this.doUploadResult(file, param, true);
        })
        .catch(() => {
          this.doUploadResult(file, param, false);
        });
    },
    doUploadOss: function(file, param) {
      var ossData = new FormData();
      ossData.append("name", param.name);
      ossData.append("key", param.key);
      ossData.append("policy", param.policy);
      ossData.append("OSSAccessKeyId", param.accessid);
      ossData.append("success_action_status", 200);
      ossData.append("signature", param.signature);
      ossData.append("file", file.file, param.name);
      Http.post(param.host, ossData, {
        timeout: 1000 * 60 * 60,
        headers: { "Content-Type": "multipart/form-data;" },
        onUploadProgress: progress => {
          var percent = parseInt(
            ((progress.loaded / progress.total) * 100) | 0
          );
          this.doShowProgress(file, percent);
        }
      })
        .then(() => {
          this.doUploadResult(file, param, true);
        })
        .catch(() => {
          this.doUploadResult(file, param, false);
        });
    },
    doShowProgress: function(file, percent) {
      this.$set(
        this.files.filter(f => f.id === file.file.uid)[0],
        "percent",
        percent
      );
    },
    doUploadResult: function(file, param, state) {
      var resource = {
        id: param.resourceId,
        state: state ? 1 : -1,
        content: JSON.stringify(param.store)
      };
      ResourceApi.policyResult(resource).then(() => {
        this.$set(
          this.files.filter(f => f.id === file.file.uid)[0],
          "status",
          state ? "success" : "exception"
        );
        setTimeout(() => {
          this.endUpload(file, param, state);
        }, 1000);
      });
    },
    endUpload: function(file) {
      var index = -1;
      this.files.forEach((f, i) => {
        if (f.id === file.file.uid) {
          index = i;
        }
      });
      this.files.splice(index, 1);
      if (this.files.length == 0) {
        this.showProgress = false;
        this.$emit("upload:end", true);
      }
    }
  }
};
